<template>
	<view>
		<!-- 使用搜索定位组件 -->
		<search-location @search="search"></search-location>

		<!-- 机构列表 start -->
		<view class="content" @scroll="onScroll" style="height: 100vh; overflow-y: auto;">
			<view class="institution-model">
				<view class="institution-model-one" v-for="item in institutionList" :key="item.id"
					@click="navigateToInstitutionDetail(item.id)">
					<view class="institution-model-one-img">
						<image class="institution-model-one-img-img" :src="'https://iepsy.oss-cn-beijing.aliyuncs.com/'+item.logo" mode="widthFix"></image>
					</view>
					<view class="institution-model-text">
						<view class="institution-model-text-title">
							<view class="institution-model-text-title-name">{{item.name}}</view>
							<view class="institution-model-text-title-distance">
								<view class="institution-model-text-title-distance-img">
									<image class="institution-model-text-title-distance-img-img"
										src="/static/other/address.png" mode="widthFix"></image>
								</view>
								{{item.city}}
							</view>
						</view>
						<view class="institution-model-text-title-address">{{item.address}}</view>
					</view>
				</view>
				
				<!-- 加载提示 -->
				<view v-if="loading" class="loading-tip">
					加载中...
				</view>
				<view v-if="!hasMore && institutionList.length > 0" class="no-more-tip">
					没有更多数据了
				</view>
			</view>
		</view>
		<!-- 机构列表 end -->
	</view>
</template>

<script>
	import { getAgencList } from '../../api/api.js'
	import searchLocation from '../../components/search-location/search-location.vue';
	import locationManager from '../../utils/location.js'
	export default {
		components: {
			searchLocation
		},
		data() {
			return {
				institutionList: [],
				currentPage: 1,
				pageSize: 10,
				hasMore: true,
				loading: false,
				scrollTop: 0,
				// 定位相关状态
				locationInfo: null,
				isLocating: false
			}
		},
		onShow() {
			// 检查是否有选择的城市（从城市选择页面返回）
			const selectedCity = uni.getStorageSync('selectedCity');
			if (selectedCity) {
				// 更新组件中的城市信息
				uni.$emit('updateCity', selectedCity);
				// 清除缓存
				uni.removeStorageSync('selectedCity');
				// 更新机构列表
				this.initPage();
			} else {
				// 只有在没有选择城市的情况下，才检查定位状态
				this.checkLocationStatus();
			}
		},
		onLoad(options) {
			console.log(options,'options机构详情');
			this.initPage();
			//后续计算距离使用qqmapsdk.calculateDistance({...})
		},
		onReachBottom() {
			// 页面触底时加载更多数据
			this.loadMoreData();
		},
		
		methods: {
			/**
			 * 页面初始化
			*/
			async initPage() {
				// 重置分页状态
				this.currentPage = 1;
				this.hasMore = true;
				this.institutionList = [];
				// 获取机构列表数据
				this.getAgencListData();
			},
			
			/**
			 * 检查定位状态
			 */
			async checkLocationStatus() {
				if (this.isLocating) {
					return;
				}
				
				try {
					// 检查是否已有有效定位
					const cachedLocation = locationManager.getCachedLocation();
					if (cachedLocation) {
						// console.log('📍 已有有效定位信息');
						this.locationInfo = cachedLocation;
						// 更新城市信息
						this.updateCityInfo(cachedLocation);
						return;
					}
					
					// 如果没有有效定位，发起定位请求
					// console.log('🔍 没有有效定位信息，发起定位请求...');
					this.isLocating = true;
					const location = await locationManager.getUserLocation(true);
					this.locationInfo = location;
					// console.log('✅ 定位成功，位置信息:', location);
						
					// 更新城市信息
					this.updateCityInfo(location);
						
					// 更新机构列表
					this.initPage();
					
				} catch (error) {
					console.error('❌ 定位失败:', error);
					// 定位失败时不影响用户体验，使用默认城市
					uni.showToast({
						title: '定位失败，使用默认城市',
						icon: 'none',
						duration: 2000
					});
				} finally {
					this.isLocating = false;
				}
			},
			
			/**
			 * 更新城市信息
			 */
			updateCityInfo(location) {
				if (location.cityInfo && location.cityInfo.city) {
					const cityName = location.cityInfo.city;
					// console.log('🏙️ 更新城市信息为:', cityName);
					// 通知搜索定位组件更新城市
					uni.$emit('updateCity', cityName);
				}
			},
			
			/**
			 * 获取机构列表数据
			*/
			getAgencListData() {
				if (this.loading || !this.hasMore) return;
					
				this.loading = true;
				// console.log('🖼️ 获取机构数据...', this.currentPage)
				
				// 准备请求参数
				const requestParams = {
					pagenum: this.currentPage,
					pagesize: this.pageSize
				};
				
				// 如果有定位信息，添加经纬度参数
				if (this.locationInfo && this.locationInfo.latitude && this.locationInfo.longitude) {
					requestParams.latitude = this.locationInfo.latitude;
					requestParams.longitude = this.locationInfo.longitude;
					// console.log('📍 添加定位参数:', requestParams);
				}
				
				getAgencList(requestParams).then(res => {
					// console.log('✅ 获取机构数据:', res);
					
					// 首次加载数据
					if (this.currentPage === 1) {
						this.institutionList = res || [];
					} else {
						// 追加数据
						this.institutionList = [...this.institutionList, ...(res || [])];
					}
					
					// 判断是否还有更多数据
					if (!res || res.length < this.pageSize) {
						this.hasMore = false;
					}
					
					// 加载完成
					this.loading = false;
				}).catch(error => {
					// console.error('❌ 获取机构数据:', error);
					this.loading = false;
					if (this.currentPage === 1) {
						this.institutionList = [];
					}
				});
			},
			
			/**
			 * 加载更多数据
			 */
			loadMoreData() {
				if (this.loading || !this.hasMore) return;
				this.currentPage++;
				this.getAgencListData();
			},
			
			/**
			 * 滚动监听
			 */
			onScroll(e) {
				this.scrollTop = e.detail.scrollTop;
			},
			
			search(e) {
				// console.log('搜索内容:', e);
				// 这里可以添加搜索逻辑，根据关键词筛选机构列表
			},
			// 导航到机构首页
			navigateToInstitutionDetail(id) {
				uni.navigateTo({
					url: `/pages/agency/agency?id=${id}`
				});
			}
		}
	}
</script>

<style>
	.content {
		top: 0;
		left: 0;
		background-color: white;
		width: 100%;
	}

	.institution-model {
		width: 100%;
		margin: 35rpx 0rpx;
		display: flex;
		flex-direction: column;
		 align-items: center; /* 垂直居中 */
		background-color: #F8F8F8;
	}

	.institution-model-one {
		width: 693rpx;
		    height: 460rpx;
		    border-radius: 24rpx;
		    overflow: hidden;
		    background-color: white;
		    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.5);
		    transition: all 0.3s ease;
		    margin-top: 12rpx;
		    margin-bottom: 12rpx;
		    color: #000
	}

	.institution-model-one-img {
		/* display: grid;
		place-items: center; */
		    height: 300rpx;
		    overflow: hidden;
		    display: flex;
		    justify-content: center;
		    align-items: center;
		    z-index: 20;
		    background-color: #fff;

	}

	.institution-model-one-img-img {
		    width: 90%;
		    height: 100%;
		    object-fit: cover;

	}

	.institution-model-text {
		padding: 0rpx 30rpx;
	}

	.institution-model-text-title {
		display: flex;
		justify-content: space-between;
	}

	.institution-model-text-title-name {
		font-size: 32rpx;
		font-weight: 700;
		color: #000;
		width: 500rpx;
	}

	.institution-model-text-title-distance {
		display: flex;
		align-items: center;
		color: #666;
		font-size: 28rpx;
	}

	.institution-model-text-title-distance-img {
		width: 24rpx;
		height: 24rpx;
		margin-right: 8rpx;
	}

	.institution-model-text-title-distance-img-img {
		width: 100%;
		height: 100%;
	}

	.institution-model-text-title-address {
		font-size: 28rpx;
		color: #666;
		margin-top: 16rpx;
	}
	
	/* 加载提示样式 */
	.loading-tip {
		padding: 20rpx;
		text-align: center;
		color: #999;
		font-size: 28rpx;
	}
	
	.no-more-tip {
		padding: 20rpx;
		text-align: center;
		color: #999;
		font-size: 28rpx;
	}
	.uni-searchbar{
		width: 485rpx;
	}
</style>